<?php

class Ebx_Storage_Iblock implements Ebx_Storage {

	const DEFAULT_NS = 'iblock_data_storage';

	protected $_iblockCode = null;

	protected $_iblockType = null;

	protected $_iblockId = null;

	protected $_filter = array();

	protected $_data = null;

	protected $_namespace = null;

	protected $_registry = null;

	function __construct($namespace = self::DEFAULT_NS, $registry = null) {
		$this->setNamespace($namespace);
		if (null !== $registry) {
			if (is_string($registry)) {
				$registry = Ebx_Registry_Manager::getRegistry($registry, 'array');
			}
			$this->setRegistry($registry);
		}
	}

	function read() {
		$this->_initData();
		$registry = $this->getRegistry();
		if (null !== $registry) {
			$registry->clear();
			foreach ($this->_data as $item) {
				$registry[$item['ID']] = $item;
			}
			return $registry;
		}
		return $this->_data;
	}

	function write($data = null) {
		$this->_init();

		if ($data instanceof Ebx_Registry) {
			$data = $data->toArray();
		}
		if ($data === null) {
			$registry = $this->getRegistry();
			if ($registry !== null) {
				$data = $registry->toArray();
			}
		}

		if ($data) {
			$object = new CIBlockElement();
			foreach ((array)$data as $key => $value) {
				if (is_array($value)) {
					$fields = array_merge($value, $this->_filter);
				} else {
					$fields = array_merge($this->_filter, array(
						'NAME' => (string)$value
					));
				}
				$object->Add($fields);
			}
		}
	}

	function clear() {
		$this->_initData();
		foreach ($this->_data as $item) {
			CIBlockElement::Delete($item['ID']);
		}
	}

	function isEmpty() {
		$this->_initData();
		return empty($this->_data);
	}

	function setNamespace($namespace) {
		$this->_namespace = $namespace;
	}

	function getNamespace() {
		return $this->_namespace;
	}

	function setRegistry(Ebx_Registry_Interface $registry) {
		$this->_registry = $registry;
	}

	function getRegistry() {
		return $this->_registry;
	}

	function getIblockId() {
		$this->_init();
		return $this->_iblockId;
	}

	protected function _init() {
		if ($this->_iblockId === null) {
			$this->_iblockId = Ebx_Tools_Iblock::getIdByCode($this->_iblockCode, $this->_iblockType);
			if ($this->_iblockId > 0) {
				$this->_filter = array(
					'IBLOCK_ID' => $this->_iblockId,
					'CODE' => $this->getNamespace(),
					'ACTIVE' => 'Y',
				);
			} else {
				trigger_error('iblock not found in '.__CLASS__, E_USER_ERROR);
				exit;
			}
		}
	}

	protected function _initData() {
		$this->_init();
		if ($this->_data === null) {
			$this->_data = array();
			$dbResult = CIBlockElement::GetList(false, $this->_filter, false, false, array('ID', 'IBLOCK_ID', 'CODE', 'NAME', 'SORT', 'DATE_CREATE'));
			while ($fields = $dbResult->Fetch()) {
				array_push($this->_data, $fields);
			}
		}
	}

}

?>